#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from pathlib import Path

from loguru import logger

from public.project_patch import LOG_FILE


class Logs:

    """
    TRACE < DEBUG < INFO < SUCCESS < WARNING < ERROR < CRITICAL
    """

    def __init__(
        self,
        log_file_path: str,
        file_log_level: str = "debug",
        console_log_level: str = "info",
    ):
        self.log_file_path = log_file_path
        self.delete_log_file()
        self.logger = logger
        self.logger.remove()
        self.file_handler(level=file_log_level)
        self.stdout_handler(level=console_log_level)

    def stdout_handler(self, level: str = None) -> None:
        """配置控制台输出日志"""
        self.logger.add(
            sys.stdout,
            level=level.upper(),
            colorize=True,
            format="<green>{time:%Y-%m-%d %H:%M:%S}</green> "  # 颜色>时间
            # "<m>[{process.name}]</m>-"  # 进程名
            # "<m>[{thread.name}]</m>-"  # 线程名
            "<cyan>[{module}</cyan>.<cyan>{function}</cyan>"  # 模块名.方法名
            ":<cyan>{line}]</cyan>-"  # 行数
            "<level>[{level}]</level>: "  # 等级
            "<lvl>{message}</lvl>",  # 日志内容
        )

    def file_handler(self, level: str = None) -> None:
        """配置日志文件"""
        self.logger.add(
            self.log_file_path,
            level=level.upper(),
            format="{time:YYYY-MM-DD HH:mm:ss} "
            # "[{process.name}]-"
            # "[{thread.name}]-"
            "[{module}.{function}:{line}]-[{level}]:{message}",
            rotation="10 MB",
            encoding="utf-8",
        )

    def delete_log_file(self):
        """删除旧的日志"""
        log_file_path = Path(self.log_file_path)
        if log_file_path.exists():
            log_file_path.unlink()


log = Logs(
    log_file_path=LOG_FILE, file_log_level="info", console_log_level="info"
).logger

if __name__ == "__main__":
    log.debug("这是一条DEBUG级别的日志，仅会出现在日志文件中。")
    log.info("这是一条INFO级别的日志，会同时出现在控制台和日志文件中。")
    log.warning("这是一条WARNING级别的日志。")
    log.error("这是一条ERROR级别的日志。")
